package com.project.controller;

import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
@SuppressWarnings("all")
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    IUserService service;

    /**
     * 登陆
     *
     * @param username 用户名
     * @param pwd      密码
     * @param request  请求对象
     * @return 登陆成功将对象放入到session中，并且返回ok，登陆失败则返回no
     */
    @RequestMapping("land")
    public String login(String username, String pwd, HttpServletRequest request) {
        UserBean user = service.login(username, pwd);

        if (user != null) {
            request.getSession().setAttribute("loginUser", user);
            return "ok";
        }
        return "no";
    }

    /**
     * 用户注册
     *
     * @param user 用户对象
     * @return 注册成功返回ok
     */
    @RequestMapping("add")
    public String add(UserBean user) {
        service.add(user);
        return "ok";
    }

    /**
     * 用户名查重
     *
     * @param username 用户名
     * @return 如果可以使用返回ok 如果已存在返回no
     */
    @RequestMapping("findByUsername")
    public String findByUsername(String username) {
        if (service.findByUsername(username)) {
            return "ok";
        }
        return "no";
    }

    /**
     * 查询登陆用户
     *
     * @param request
     * @return
     */
    @RequestMapping("getUser")
    public UserBean getUser(HttpServletRequest request) {
        UserBean user = (UserBean) request.getSession().getAttribute("loginUser");

        if (user != null) {
            return user;
        }
        return null;
    }

    /**
     * 按照id查询用户信息
     * @param id
     * @return
     */
    @RequestMapping("findById")
    public UserBean findById(Integer id){
       return service.findById(id);
    }
}
